package com.tacc.tyun.controller;

import com.alibaba.fastjson.JSONObject;
import com.tacc.tyun.base.BaseConstant;
import com.tacc.tyun.common.oss.CloudStorageConfig;
import com.tacc.tyun.model.SysConfig;
import com.tacc.tyun.model.info.ReturnInfo;
import com.tacc.tyun.service.SysConfigService;
import com.tacc.tyun.service.SysOssService;
import com.tacc.tyun.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;


/**
* 系统配置文件
* 使用key value，用json来保存
* @author congcong tao
* @date 2017/9/7 14:05
*/
@Controller
@RequestMapping("/sysConfig")
public class SysConfigController {

    private static Logger LOGGER= LoggerFactory.getLogger(SysConfigController.class);

    @Autowired
    private SysOssService sysOssService;
    @Autowired
    private SysConfigService sysConfigService;

    //配置云存储
    @RequestMapping("/ossView")
    public ModelAndView sysOssConfig(){
        //直接去数据库查询有无这一配置
        String key=ConfigConstant.CLOUD_STORAGE_CONFIG_KEY;
        CloudStorageConfig config = sysConfigService.getConfigObject(key, CloudStorageConfig.class);
        return new ModelAndView("oss/sysOssConfig").addObject(config);
    }

    /**
     * 新增图片
     */
    @RequestMapping(value = "/UpdateOrAddEntity",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject UpdateOrAddEntity(HttpServletRequest request, String jsonData) throws IOException {
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();
        //判断配置是否存在
        String key=ConfigConstant.CLOUD_STORAGE_CONFIG_KEY;
        SysConfig sysConfig = sysConfigService.selectByPrimaryKey(key);
        if(sysConfig==null){
            sysConfig=new SysConfig();
            sysConfig.setKey(key);
            sysConfig.setValue(jsonData);
            sysConfig.setCreatetime(new Date());
            sysConfig.setUpdatetime(sysConfig.getCreatetime());
            int id=sysConfigService.insert(sysConfig);
            if(id <= 0){
                returnInfo=new ReturnInfo(BaseConstant.FAIL,BaseConstant.DATABASE_ERROR_INSERT);
            }
        }else{
            sysConfig.setValue(jsonData);
            sysConfig.setUpdatetime(sysConfig.getCreatetime());
            int id=sysConfigService.updateByPrimaryKey(sysConfig);
            if(id <= 0){
                returnInfo=new ReturnInfo(BaseConstant.FAIL,BaseConstant.DATABASE_ERROR_UPDATE);
            }
        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }

}
